//index.js
//获取应用实例
const app = getApp()
const sss = require('../son/SHA-1/sha.js');
const totp = require('../son/SHA-1/totp.js');

var head_left_judge = false;
var touch_start_point=null;
var touch_end_point = null;
var box_true_array=[true,false,false];
var check_out_who = 0;
let cache_jud=false;
var num=0;
var num_jud=true;
var charts_need_array=[];
var weekNum1=0;

Page({
  data: {
    colorArrays: ["#FBCF6D", "#C8C8F7", "#FEBCD9", "#5FE1D1", "#8BD3F9", "#64E1B1", "#12AEF3", "#E29AAD"],
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),

    username: '',
    pwd: '',
    pwd2: '',
    pwd3: '',
    sid:"",

    animation1: {},
    mask_fade:{},
    head_left_in:{},
    mask_hide:false,
    hid_jie:true,

    box_true:[true,false,false],
    index_page_1:{},
    index_page_2:{},
    index_page_3:{},

    progress_txt: '正在加载数据',
    count: 0, // 设置 计数器 初始为0
    countTimer: null // 设置 定时器 初始为null   progress~~~~~
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  head_left_tap:function(){
    this.onLoad();
  },
  onPullDownRefresh:function(){
      this.onShow();
  }
  ,
  dengru: function(e){

    
    wx.navigateTo({
      url: '../index/index(1)'
    })
   
  },
  
  onLoad: function () {
    
    
  },
  getUserInfo: function(e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  onReady:function(){
    if (app.globalData.sid == null && app.globalData.sid == '') {
      wx.showToast({
        title: '请登入',
      })
      wx.switchTab({
        url: 'pages/index/index(1)'
      })
    }
  },
  onShow: function () {
    //掌上武大Tim
    wx.getStorage({
      key: 'stdNumber',
      success: function (res) {
        if (res.data.length != 13) {
          wx.showToast({
            title: '账号有误',
            duration: 1500
          })
        }
      },
      fail: function () {
        wx.showToast({
          title: '请登入',
          duration: 1500
        })
        wx.switchTab({
          url: 'index(1)'
        })
      }
    })

    var _this = this;
    if (app.globalData.sid != null) {
      _this.setData({
        sid: app.globalData.sid,
      })
    }
    else {
      _this.setData({
        sid: "尚未登入",
      })
    }//

    //-----数据获取
      var _this = this;
      wx.getStorage({
        key: 'wifiNumber',
        success: function (res) {
          let cache = res.data;
          app.globalData.pwd_wifi = cache;
          wx.getStorage({
            key: 'stdNumber',
            success: function (res) {
              let cache = res.data;
              if (cache.length == 13) {
                app.globalData.sid = cache;
              }
              wx.getStorage({
                key: 'eduNumber',
                success: function (res) {
                  let cache = res.data;
                  app.globalData.pwd = cache;
                  wx.getStorage({
                    key: 'libNumber',
                    success: function (res) {

                      if (app.globalData.sid != null && app.globalData.sid.length == 13) {
                        _this.setData({
                          sid: app.globalData.sid,
                        })
                      }
                      else {
                        _this.setData({
                          sid: "尚未登入",
                        })
                      }//页面初始化账户信息


                      let cache = res.data;
                      app.globalData.pwd_lib = cache;

                      //数据的获取
                      var sid = app.globalData.sid;
                      var pwd_edu = app.globalData.pwd;
                      var pwd_lib = app.globalData.pwd_lib;
                        

                      var a =
                        wx.request({
                          url: 'https://api.ziqiang.net.cn/token/', //仅为示例，并非真实的接口地址
                          method: "GET",
                          data: {
                            sid: sid,
                            pwd_edu: pwd_edu,
                            pwd_lib: pwd_lib,
                            binding_type: 2
                          },
                          dataType: JSON,
                          header: {
                            'content-type': 'application/json' // 默认值
                          },
                          success: function (res) {
                            _this.setData({
                              isChecked: false,
                            })

                            wx.showToast({
                              title: '登入成功',
                              icon: 'success',
                              duration: 2000,
                            })
                            _this.setData({
                              isAccount: true,
                            })

                            var data = JSON.parse(res.data);

                            app.globalData.Token = data.token;
                            var totpSECRET_KEY = sss.getEncodeString('+.a*vD@JrLYauz(M)HA^=}sh');
                            var secret_key = totp.updateOtp(totpSECRET_KEY);
                            //totp.getCode(totpSECRET_KEY)
                            var timestamp = Math.round(new Date().getTime() / 1000);
                            var timestampstr = timestamp.toString();//获取unix时间戳字符串
                            var ran = Math.ceil(Math.random() * 1000000000);
                            var ranstr = ran.toString();
                            var arr = new Array(3);
                            arr[0] = secret_key;
                            arr[1] = timestampstr;
                            arr[2] = ranstr;
                            arr = arr.sort();//字典序排序
                            var mix = arr[0] + arr[1] + arr[2];
                            var sha1 = sss.de2(mix).toString();//sha1算法
                              var a =
                                  wx.request({
                                      url: 'https://api.ziqiang.net.cn/settings/?name=term_begin_date,term_now_year,term_now_semester', //仅为示例，并非真实的接口地址
                                      method: "GET",
                                      data: {

                                      },
                                      dataType: JSON,
                                      header: {
                                          'content-type': 'application/json', // 默认值
                                          'Authorization': 'Token ' + app.globalData.Token,
                                          'x-zswd-signature': sha1,
                                          'x-zswd-timestamp': timestamp,
                                          'x-zswd-nonce': ran,
                                      },
                                      success: function (res) {

                                          var data = JSON.parse(res.data);
                                          app.globalData.term_now_year = data.term_now_year;
                                          app.globalData.term_begin_date = data.term_begin_date;
                                          app.globalData.term_now_semester = data.term_now_semester-1;
                                      },
                                      Error: function (res) {
                                          wx.showToast({
                                              title: '登入失败',
                                              icon: 'cancel',
                                              duration: 2000,
                                          })
                                      }
                                  })
                            var b =
                              wx.request({
                                url: 'https://api.ziqiang.net.cn/courses/', //仅为示例，并非真实的接口地址
                                method: "GET",
                                data: {

                                },
                                dataType: JSON,
                                header: {
                                  'content-type': 'application/json', // 默认值
                                  'Authorization': 'Token ' + app.globalData.Token,
                                  'x-zswd-signature': sha1,
                                  'x-zswd-timestamp': timestamp,
                                  'x-zswd-nonce': ran,
                                },
                                success: function (res) {
                                  let d = new Date();
                                    var day1 = new Date(app.globalData.term_begin_date);
                                    day1 = new Date(Date.parse(app.globalData.term_begin_date.replace(/-/g, '/')));
                                  
                                  let day_cache = d.getFullYear().toString() + '-' + (d.getMonth() + 1).toString() + '-' + d.getDate().toString();
                                  var day2 = new Date(day_cache);
                                  day2 = new Date(Date.parse(day_cache.replace(/-/g, '/')));

                                  weekNum1 = Math.ceil((day2 - day1) / (1000 * 60 * 60 * 24) / 7);
                                  weekNum1 = weekNum1;
                                  var data = JSON.parse(res.data);
                                  app.globalData.Course_Grade = data;
                                  
                                  //////////////////////////////////////


                                  function unique(arr) {
                                    var result = [];
                                    for (var i = 0; i < arr.length; i++) {
                                      if (result.indexOf(arr[i]) == -1) {
                                        result.push(arr[i])
                                      }
                                    }
                                    return result;
                                  }
                                  //unique备用函数

                                  var lesson_result = {};
                                  var lesson_result_Array = [];
                                  for (let i = 0; i < app.globalData.Course_Grade.length; i++) {
                                    for (let j = 0; j < app.globalData.Course_Grade[i].lessons_time.length; j++) {

                                      lesson_result = {
                                        "xqj": app.globalData.Course_Grade[i].lessons_time[j].weekday,
                                        "skjc": app.globalData.Course_Grade[i].lessons_time[j].class_begin,
                                        "skcd": app.globalData.Course_Grade[i].lessons_time[j].class_over - app.globalData.Course_Grade[i].lessons_time[j].class_begin + 1,
                                        "kcmc": app.globalData.Course_Grade[i].lessons_time[j].location,
                                        "kcmd": app.globalData.Course_Grade[i].name + '\n'
                                      }
                                      if (weekNum1 <= app.globalData.Course_Grade[i].lessons_time[j].week_to && weekNum1  >= app.globalData.Course_Grade[i].lessons_time[j].week_from && app.globalData.Course_Grade[i].year == app.globalData.term_now_year && app.globalData.Course_Grade[i].semester == app.globalData.term_now_semester) {
                                        lesson_result_Array.push(lesson_result);
                                      }
                                    }
                                  }
                                  if (num == 5) { num_jud = false }
                                  if (res.data == null && lesson_result_Array[0] == null && num_jud) {
                                    num = num + 1;
                                    _this.onLoad();
                                  }
                                  let weekday = new Date().getDay();
                                  if (weekday == 0) weekday = 7;
                                  if (charts_need_array[0] == null) {
                                    for (let i = 0; i < lesson_result_Array.length; i++) {
                                      if (lesson_result_Array[i].xqj == weekday) {//watch this
                                        if (lesson_result_Array[i].kcmd.length > 12) {
                                          lesson_result_Array[i].kcmd = lesson_result_Array[i].kcmd.slice(0, 12) + '...' + '\n';
                                        }
                                        charts_need_array.push(lesson_result_Array[i])
                                      }
                                    }
                                    for (let i = 0; i < charts_need_array.length; i++) {
                                      charts_need_array[i].skcd = charts_need_array[i].skcd + charts_need_array[i].skjc - 1;
                                    }
                                  }
                                  if (charts_need_array.length == 0) {
                                    var empty_result = {
                                      "xqj": '',
                                      "skjc": '',
                                      "skcd": '',
                                      "kcmc": '',
                                      "kcmd": '今日无事'
                                    }
                                    _this.setData({
                                      hid_jie: false
                                    })
                                    charts_need_array.push(empty_result);
                                  }
                                    function sortNumber(a, b) {
                                        return a.skjc - b.skjc;
                                    }
                                    charts_need_array = charts_need_array.sort(sortNumber);
                                  _this.setData({
                                    Course_list: charts_need_array,
                                  })
                                  if (num == 5) { num_jud = false }
                                  if (charts_need_array[0] == null && num_jud) {
                                    num = num + 1;
                                    _this.onLoad();
                                  }
                                  ////////////////////////////////
                                },
                                Error: function (res) {
                                  wx.showToast({
                                    title: '登入失败',
                                    icon: 'cancel',
                                    duration: 2000,
                                  })
                                }
                              })

                            

                         
                   
                            /*var f =
                              wx.request({
                                url: 'https://api.ziqiang.net.cn/courses/grade', //仅为示例，并非真实的接口地址
                                method: "GET",
                                data: {
                                  "instructor":"李美幸",
                                },
                                dataType: JSON,
                                header: {
                                  'content-type': 'application/json', // 默认值
                                  'Authorization': 'Token ' + app.globalData.Token,
                                  'x-zswd-signature': sha1,
                                  'x-zswd-timestamp': timestamp,
                                  'x-zswd-nonce': ran,
                                },
                                success: function (res) {
      
                                  var data = JSON.parse(res.data);
                                 
      
                                },
                                Error: function (res) {
                                  wx.showToast({
                                    title: '登入失败',
                                    icon: 'cancel',
                                    duration: 2000,
                                  })
                                }
                              })*/
                          },
                          Error: function (res) {
                            wx.showToast({
                              title: '登入失败',
                              icon: 'cancel',
                              duration: 2000,
                            })
                          }
                        })
                    },

                  })//三部获取图书馆密码
                },
              })//二步获取

            },
            fail: function () {
              _this.setData({
                sid: '.尚未登入.',
              })
            },

          })//一步获取账号
        }
      })//四步获取wifi密码
      //各种数据的获取



      if (app.globalData.userInfo) {
        this.setData({
          userInfo: app.globalData.userInfo,
          hasUserInfo: true
        })
      } else if (this.data.canIUse) {
        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        app.userInfoReadyCallback = res => {
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      } else {
        // 在没有 open-type=getUserInfo 版本的兼容处理
        wx.getUserInfo({
          success: res => {
            app.globalData.userInfo = res.userInfo
            this.setData({
              userInfo: res.userInfo,
              hasUserInfo: true
            })
          }
        })
      }//网络请求
    
      
  },
 

  onReady: function () {

  },

  intoLog:function(){
    wx.navigateTo({
      url: '../logs/logs'
    })
  },

  
  intoLife: function () {
    cache_jud=!cache_jud;
    if(cache_jud){
    let animation2 = wx.createAnimation({
      transformOrigin: "50% 50%",
      duration: 1300,
      timingFunction: "ease",
      delay: 0
    });
    animation2.left('10%').step();
    this.setData({
      button_block_ani: animation2.export()
    });
    }
    else{
      let animation2 = wx.createAnimation({
        transformOrigin: "50% 50%",
        duration: 1000,
        timingFunction: "ease",
        delay: 0
      });
      animation2.left('-100%').step();
      this.setData({
        button_block_ani: animation2.export()
      });
    }
  },
  intoCourse: function () {
    wx.navigateTo({
      url: '../Course/course'
    })
  },
  intoWifi: function () {
    wx.navigateTo({
      url: '../son/wifi/wifi_sign_in'
    })
  },
  intochengji: function () {
    wx.navigateTo({
      url: '../son/Course_grade'
    })
  },
  intozhaoshu: function () {
    wx.navigateTo({
      url: '../son/lend/book'
    })
  },
  intojieyuejilu: function () {
    wx.navigateTo({
      url: '../son/lend/lend_book'
    })
  },


})

